package com.example.mcp;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 前台服务 - 用于保持 MCP 服务器持续运行
 * 防止被系统杀死
 */
public class McpServerService extends Service {
    
    private static final Logger logger = LoggerFactory.getLogger(McpServerService.class);
    private static final String CHANNEL_ID = "MCP_SERVER_CHANNEL";
    private static final int NOTIFICATION_ID = 1001;
    
    private final IBinder binder = new McpServerBinder();
    private Thread weatherServerThread;
    private Thread chatServerThread;
    private AdvancedWeatherMcpServer weatherServerInstance;
    private ChatMcpServer chatServerInstance;
    private boolean isWeatherServerRunning = false;
    private boolean isChatServerRunning = false;
    private WakeLockManager wakeLockManager;
    
    public class McpServerBinder extends Binder {
        McpServerService getService() {
            return McpServerService.this;
        }
    }
    
    @Override
    public void onCreate() {
        super.onCreate();
        logger.info("🚀 McpServerService 创建");
        createNotificationChannel();
        
        // 初始化电源锁管理器
        wakeLockManager = new WakeLockManager(this);
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        logger.info("📡 启动 MCP 服务器前台服务");
        
        // 获取电源锁防止 CPU 休眠
        if (wakeLockManager != null) {
            wakeLockManager.acquireWakeLock();
        }
        
        // 创建前台通知
        Notification notification = createNotification();
        startForeground(NOTIFICATION_ID, notification);
        
        // 启动 MCP 服务器
        startMcpServers();
        
        // 返回 START_STICKY 确保服务被杀死后自动重启
        return START_STICKY;
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }
    
    @Override
    public void onDestroy() {
        logger.info("🛑 McpServerService 销毁");
        stopMcpServers();
        
        // 释放电源锁
        if (wakeLockManager != null) {
            wakeLockManager.cleanup();
        }
        
        super.onDestroy();
    }
    
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                CHANNEL_ID,
                "MCP 服务器服务",
                NotificationManager.IMPORTANCE_LOW
            );
            channel.setDescription("保持 MCP 服务器持续运行");
            channel.setShowBadge(false);
            
            NotificationManager manager = getSystemService(NotificationManager.class);
            if (manager != null) {
                manager.createNotificationChannel(channel);
            }
        }
    }
    
    private Notification createNotification() {
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
            this, 0, notificationIntent, 
            PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
        );
        
        // 获取电源锁状态信息
        String wakeLockStatus = "";
        if (wakeLockManager != null) {
            wakeLockStatus = wakeLockManager.isWakeLockAcquired() ? " (CPU保持运行)" : " (CPU可能休眠)";
        }
        
        return new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("🌤️💬 MCP 服务器")
            .setContentText("天气和聊天服务器正在运行中..." + wakeLockStatus)
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .setContentIntent(pendingIntent)
            .setOngoing(true)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .setCategory(NotificationCompat.CATEGORY_SERVICE)
            .build();
    }
    
    private void startMcpServers() {
        startWeatherServer();
        startChatServer();
    }
    
    private void startWeatherServer() {
        if (isWeatherServerRunning) {
            logger.warn("⚠️ 天气MCP服务器已在运行");
            return;
        }
        
        weatherServerThread = new Thread(() -> {
            try {
                logger.info("🌤️ 正在启动天气MCP服务器...");
                isWeatherServerRunning = true;
                weatherServerInstance = new AdvancedWeatherMcpServer();
                weatherServerInstance.start();
                // 阻塞直到线程被打断
                while (!Thread.currentThread().isInterrupted()) {
                    try { Thread.sleep(1000); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); }
                }
            } catch (Exception e) {
                logger.error("❌ 天气MCP服务器启动失败", e);
                isWeatherServerRunning = false;
            }
        });
        
        weatherServerThread.setName("WeatherMcpServerThread");
        weatherServerThread.setDaemon(false);
        weatherServerThread.start();
        
        logger.info("✅ 天气MCP服务器线程已启动");
    }
    
    private void startChatServer() {
        if (isChatServerRunning) {
            logger.warn("⚠️ 聊天MCP服务器已在运行");
            return;
        }
        
        chatServerThread = new Thread(() -> {
            try {
                logger.info("💬 正在启动聊天MCP服务器...");
                isChatServerRunning = true;
                chatServerInstance = new ChatMcpServer();
                chatServerInstance.start();
                // 阻塞直到线程被打断
                while (!Thread.currentThread().isInterrupted()) {
                    try { Thread.sleep(1000); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); }
                }
            } catch (Exception e) {
                logger.error("❌ 聊天MCP服务器启动失败", e);
                isChatServerRunning = false;
            }
        });
        
        chatServerThread.setName("ChatMcpServerThread");
        chatServerThread.setDaemon(false);
        chatServerThread.start();
        
        logger.info("✅ 聊天MCP服务器线程已启动");
    }
    
    private void stopMcpServers() {
        logger.info("🛑 正在停止 MCP 服务器...");
        stopWeatherServer();
        stopChatServer();
    }
    
    private void stopWeatherServer() {
        logger.info("🛑 正在停止天气MCP服务器...");
        try {
            if (weatherServerInstance != null) {
                weatherServerInstance.stop();
            }
        } catch (Exception e) {
            logger.warn("停止天气服务器实例时出错: {}", e.toString());
        }
        if (weatherServerThread != null && weatherServerThread.isAlive()) {
            weatherServerThread.interrupt();
            try { weatherServerThread.join(2000); } catch (InterruptedException ignored) {}
        }
        isWeatherServerRunning = false;
        weatherServerThread = null;
        weatherServerInstance = null;
    }
    
    private void stopChatServer() {
        logger.info("🛑 正在停止聊天MCP服务器...");
        try {
            if (chatServerInstance != null) {
                chatServerInstance.stop();
            }
        } catch (Exception e) {
            logger.warn("停止聊天服务器实例时出错: {}", e.toString());
        }
        if (chatServerThread != null && chatServerThread.isAlive()) {
            chatServerThread.interrupt();
            try { chatServerThread.join(2000); } catch (InterruptedException ignored) {}
        }
        isChatServerRunning = false;
        chatServerThread = null;
        chatServerInstance = null;
    }
    
    public boolean isServerRunning() {
        return isWeatherServerRunning || isChatServerRunning;
    }
    
    public boolean isWeatherServerRunning() {
        return isWeatherServerRunning;
    }
    
    public boolean isChatServerRunning() {
        return isChatServerRunning;
    }
}
